#!/usr/bin/env node

const http = require('http'),
      fs   = require('fs'),
      qs   = require('querystring');
let items = [];


function genPage(){
  let html = fs.readFileSync('./template.html').toString('utf8');
  html = html.replace('*',items.map( i => '<li>' + i + '</li>').join('\n'));
  return html;
}

http.createServer((req,res)=>{
  if(req.url !== '/'){
    res.statusCode = 404;
    res.setHeader('Content-Type','text/html');
    res.end('<h1>not found</h1>');
  }else{

    let data = '';
    req.on('data',chunck => data += chunck);
   
    
    req.on('end',()=>{
      
      console.log(`data:${data}`);
      console.log(qs.parse(data));
      let item = qs.parse(data).item;
      
      console.log(`item:${item}`);

      if(item !== '' &&  typeof item !== 'undefined') items.push(item);
      
      res.writeHead(200,{
        'Content-Type':'text-html',
        'Content-Length':Buffer.byteLength(genPage())
      });

      res.end(genPage());

    });

  }

}).listen(8080);
